package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import restaurant.MenuCategory;
import restaurant.MenuItem;

/**
 * Servlet implementation class MenuItemAddEdit
 */
@WebServlet(urlPatterns={"/Add%20Menu%20Item","Edit%20Menu%20Item"})
public class MenuItemAddEdit extends Menu {
    private static final long serialVersionUID = 201212030048L;

    @Override
    protected Map<String, String> getLinkMap() {
        return LinkData.getAdminLinkMap();
    }

    @Override
    protected String getDispatcherPage() {
        return "/WEB-INF/menu_item_add_edit.jsp";
    }

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        final String idString = req.getParameter("id");
        final EntityManager em = _emf.createEntityManager();
        if (null != idString && !idString.isEmpty()) {
            MenuItem menuItem = em.find(MenuItem.class, idString);
            if (null != menuItem) {
                req.setAttribute("menuItem", menuItem);
            } else {
                //TODO: log error, display to user
            }
        }

        final TypedQuery<MenuCategory> q = em.createQuery("select c from MenuCategory c", MenuCategory.class);
        final List<MenuCategory> categories = q.getResultList();

        req.setAttribute("categories", categories);

        for (final MenuCategory category : q.getResultList()) {
            final List<MenuItem> menuItems = new ArrayList<>();
            TypedQuery<MenuItem> q2 = em.createQuery("select m from MenuItem m where m.category = :category", MenuItem.class);
            q2.setParameter("category", category);
            menuItems.addAll(q2.getResultList());
            Collections.sort(menuItems, new MenuSorter());

            menuItemsByCategory.put(category.getName(), menuItems);
        }

        req.setAttribute("menuItemsByCategory", menuItemsByCategory);
        req.setAttribute("tagIcons", tagIcons);

        req.setAttribute("namesToPages", getLinkMap());
        req.getRequestDispatcher(getDispatcherPage()).forward(req, resp);

        em.close();
    }
}
